// appOpener.js
const APP_SCHEMES = {
  ios: {
    meituan: "423084029",
    dianping: "351091731",
    gaode: "461703208",
    weixin: "836500024",
    douyin: "1142110895",
  },
  android: {
    meituan: "com.sankuai.meituan",
    dianping: "com.dianping.v1",
    gaode: "com.autonavi.minimap",
    weixin: "com.tencent.mm",
    douyin: "com.ss.android.ugc.aweme",
  },
};

const STORE_SCHEMES = {
  apple: "itms-apps://apps.apple.com/cn/app/id",
  huawei: "appmarket://details?id=",
  vivo: "vivoMarket://details?id=",
  oppo: "market://details?id=",
  xiaomi: "mimarket://details?id=",
  default: "market://details?id=",
};

class AppOpener {
  constructor(options = {}) {
    const app = getApp();
    this.platform = app.globalData.systemInfo.platform;
    this.systemInfo = app.globalData.systemInfo;

    this.config = {
      scheme: options.scheme || "",
      ios: options.ios || "",
      android: options.android || "",
      timeout: options.timeout || 2500,
    };

    this.startTime = 0;
    this.pageHidden = false;
    this.launchChecked = false;
  }

  open() {
    return new Promise((resolve, reject) => {
      this.startTime = Date.now();
      this.pageHidden = false;
      this.launchChecked = false;

      // 设置页面隐藏监听
      const visibilityCallback = () => {
        const hidden = this.getHiddenProperty();
        if (document[hidden]) {
          this.pageHidden = true;
          document.removeEventListener(
            this.getVisibilityChangeEvent(),
            visibilityCallback
          );
          if (!this.launchChecked) {
            this.launchChecked = true;
            resolve({ success: true });
          }
        }
      };

      document.addEventListener(
        this.getVisibilityChangeEvent(),
        visibilityCallback
      );

      // 尝试打开应用
      this.tryLaunchApp();

      // 检查是否成功打开
      setTimeout(() => {
        if (!this.launchChecked) {
          this.launchChecked = true;
          document.removeEventListener(
            this.getVisibilityChangeEvent(),
            visibilityCallback
          );

          // 如果页面没有隐藏，说明应用可能未安装
          if (!this.pageHidden) {
            uni.showModal({
              title: "提示",
              content: "是否跳转到应用商店下载？",
              success: (res) => {
                if (res.confirm) {
                  this.goToStore();
                }
                reject({
                  success: false,
                  gotoStore: res.confirm,
                });
              },
            });
          }
        }
      }, this.config.timeout);
    });
  }

  tryLaunchApp() {
    if (this.platform === "ios") {
      location.href = this.config.scheme;
    } else {
      // Android 使用 iframe 方式
      const iframe = document.createElement("iframe");
      iframe.style.cssText = "display:none;border:0;width:0;height:0;";
      iframe.src = this.config.scheme;

      document.body.appendChild(iframe);
      setTimeout(() => {
        document.body.removeChild(iframe);
      }, 1000);
    }
  }

  goToStore() {
    let storeUrl;

    if (this.platform === "ios") {
      storeUrl = `${STORE_SCHEMES.apple}${this.config.ios}`;
    } else {
      const brand = this.getBrand();
      const storeScheme = STORE_SCHEMES[brand] || STORE_SCHEMES.default;
      storeUrl = `${storeScheme}${this.config.android}`;
    }

    setTimeout(() => {
      location.href = storeUrl;
    }, 100);
  }

  getBrand() {
    const ua = this.systemInfo.model.toLowerCase();
    if (ua.includes("huawei") || ua.includes("honor")) return "huawei";
    if (ua.includes("vivo")) return "vivo";
    if (ua.includes("oppo")) return "oppo";
    if (ua.includes("xiaomi") || ua.includes("redmi")) return "xiaomi";
    return "default";
  }

  getHiddenProperty() {
    const prefixes = ["hidden", "webkitHidden", "mozHidden", "msHidden"];
    for (const prefix of prefixes) {
      if (typeof document[prefix] !== "undefined") {
        return prefix;
      }
    }
    return "hidden";
  }

  getVisibilityChangeEvent() {
    const prefixes = ["", "webkit", "moz", "ms"];
    for (const prefix of prefixes) {
      const eventName = prefix + (prefix ? "V" : "v") + "isibilitychange";
      if (typeof document[`on${eventName}`] !== "undefined") {
        return eventName;
      }
    }
    return "visibilitychange";
  }
}

export default AppOpener;
